
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @module message-manager
 * @author: Hjava
 * @description: 消息管理模块
 * @since: 2018-07-23 13:02:30
 */
var create_cancel_message_1 = __webpack_require__(/*! _Eutils/create-cancel-message */ "./src/extra/utils/create-cancel-message.ts");
var create_message_1 = __webpack_require__(/*! _Eutils/create-message */ "./src/extra/utils/create-message.ts");
var create_pub_tt_message_1 = __webpack_require__(/*! _Eutils/create-pub-tt-message */ "./src/extra/utils/create-pub-tt-message.ts");
var event_emitter_1 = __webpack_require__(/*! _Eutils/event-emitter */ "./src/extra/utils/event-emitter.ts");
var map_1 = __webpack_require__(/*! _Eutils/map */ "./src/extra/utils/map.ts");
var messageSorter_1 = __webpack_require__(/*! _Eutils/messageSorter */ "./src/extra/utils/messageSorter.ts");
var opposite_read_creator_1 = __webpack_require__(/*! _Eutils/opposite-read-creator */ "./src/extra/utils/opposite-read-creator.ts");
var parse_message_1 = __webpack_require__(/*! _Eutils/parse-message */ "./src/extra/utils/parse-message.ts");
var parse_data_message_1 = __webpack_require__(/*! _Eutils/parse-data-message */ "./src/extra/utils/parse-data-message.ts");
var sessionIdProcessor_1 = __webpack_require__(/*! _Eutils/sessionIdProcessor */ "./src/extra/utils/sessionIdProcessor.ts");
var im_constant_1 = __webpack_require__(/*! _im/im.constant */ "./src/core/im/im.constant.ts");
var pub_constant_1 = __webpack_require__(/*! _pub/pub.constant */ "./src/core/pub/pub.constant.ts");
var constant_1 = __webpack_require__(/*! _util/constant */ "./src/core/utils/constant.ts");
var promise_1 = __webpack_require__(/*! _util/promise */ "./src/core/utils/promise.ts");
var userData_1 = __webpack_require__(/*! _util/userData */ "./src/core/utils/userData.ts");
var models_1 = __webpack_require__(/*! ../models */ "./src/extra/models/index.ts");
var config_manager_1 = __webpack_require__(/*! ./config-manager */ "./src/extra/managers/config-manager.ts");
var constant_2 = __webpack_require__(/*! ../../core/utils/constant */ "./src/core/utils/constant.ts");
var log_1 = __webpack_require__(/*! ./../utils/log */ "./src/extra/utils/log.ts");
var message_util_1 = __webpack_require__(/*! ./../utils/message-util */ "./src/extra/utils/message-util.ts");
var timer_1 = __webpack_require__(/*! _util/timer */ "./src/core/utils/timer.ts");
var localData_1 = __webpack_require__(/*! _util/localData */ "./src/core/utils/localData.ts");
var constant_3 = __webpack_require__(/*! _util/constant */ "./src/core/utils/constant.ts");
var message_report_1 = __webpack_require__(/*! ../statistics/message-report */ "./src/extra/statistics/message-report.ts");
var BIG_MID = '9223372036854775807'; //Long型最大值
var BIG_TIME = '9223372036854775807'; //Long型最大值,直接复用
var MESSAGE_TIMEOUT_TIME = 5 * 1000;
var MessageManager = /** @class */ (function () {
    function MessageManager() {
        var _this = this;
        // 是否继续接受消息
        this._shouldReceiveMessage = true;
        this.mtdx = {};
        this._messageMap = new map_1.default();
        this._queueMap = new map_1.default();
        this._localMessageMap = new map_1.default();
        this._cancelQueueMap = new map_1.default();
        this._oppositeReadMap = new map_1.default();
        event_emitter_1.default.on(event_emitter_1.EVENT_NAME.AUTH_SUCCESS, function () {
            // 登录成功后清空,可以保证在断网的期间可以查看以前的消息,但是未发送成功的消息保留了
            _this.deleteAllSendSuccessMessages();
        });
    }
    MessageManager.prototype.init = function (mtdx) {
        var _this = this;
        log_1.default.log('MessageManager::init');
        this.mtdx = mtdx;
        var AUTH_SUCCESS = constant_1.LOGIN_EVENT.AUTH_SUCCESS;
        var MESSAGE = constant_1.MESSAGE_EVENT.MESSAGE, ACK = constant_1.MESSAGE_EVENT.ACK, NOTICE = constant_1.MESSAGE_EVENT.NOTICE, OPPOSITE_READ = constant_1.MESSAGE_EVENT.OPPOSITE_READ, OPPOSITE_READ_ACK = constant_1.MESSAGE_EVENT.OPPOSITE_READ_ACK, PUB_OPPOSITE_READ = constant_1.MESSAGE_EVENT.PUB_OPPOSITE_READ, PUB_OPPOSITE_READ_ACK = constant_1.MESSAGE_EVENT.PUB_OPPOSITE_READ_ACK, RECEIPT_GROUP_MESSAGE = constant_1.MESSAGE_EVENT.RECEIPT_GROUP_MESSAGE, RECEIPT_GROUP_MESSAGE_ACK = constant_1.MESSAGE_EVENT.RECEIPT_GROUP_MESSAGE_ACK, PUB_MESSAGE_ADDITION = constant_1.MESSAGE_EVENT.PUB_MESSAGE_ADDITION, IM_MESSAGE_ADDITION = constant_1.MESSAGE_EVENT.IM_MESSAGE_ADDITION;
        this.mtdx.on(AUTH_SUCCESS, function () {
            _this._shouldReceiveMessage = true;
            _this.fetchOfflineDataMessage();
            _this.fetchChatListDelInfo();
        });
        this.mtdx.on(MESSAGE, function (messageDatum) {
            if (!_this._shouldReceiveMessage) {
                log_1.default.log('MessageManager::init _shouldReceiveMessage false');
                return;
            }
            // 透传消息，暂不处理，后续有需要可以向上抛出事件
            if (messageDatum.data) {
                var dataMessageObject = parse_data_message_1.default(messageDatum);
                log_1.default.log('MessageManager::init data message info:' + dataMessageObject);
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.DATA_MESSAGE, { message: dataMessageObject });
                return;
            }
            // 聊天室消息，暂不处理
            if (messageDatum.priority) {
                log_1.default.log('MessageManager::init chatroom message');
                event_emitter_1.default.emit(MESSAGE, { message: messageDatum });
                return;
            }
            messageDatum.status = models_1.Message.STATUS.STATUS_ACK;
            var message = parse_message_1.default(messageDatum);
            // Log.log('MessageManager::receive message messageDatum:' + JSON.stringify(messageDatum) + ' message:' + JSON.stringify(message))
            // 部分消息不解析时，直接抛给上层
            if (!message) {
                log_1.default.log('MessageManager::init 收到SDK不处理消息', messageDatum);
                event_emitter_1.default.emit(MESSAGE, { message: messageDatum });
                return;
            }
            // PUB 透传消息
            if (message.isTTMessage) {
                // 不做任何事情，触发MESSAGE事件
                log_1.default.log('MessageManager::init pub tt message info:' + message);
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message });
                return;
            }
            // 消息已经存在，直接丢弃即可
            if (_this.hasLocalMessageInArray(message)) {
                log_1.default.log('MessageManager::init 消息已经存在 info:' + message);
                return;
            }
            if (message.isCancel) {
                log_1.default.log('MessageManager::init receive cancel message info:' + message);
                message.status = constant_1.CANCEL_STATUS.CANCELED;
                _this.putCancelMessageInMap(message);
            }
            else {
                log_1.default.log('MessageManager::init receive message info:' + message);
                _this.putMessagesInMap(message.belongTo, message.channelId, message.sid, [message]);
            }
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message }, true);
        });
        this.mtdx.on(constant_1.MESSAGE_EVENT.D_MESSAGE_OFFLINE, function (messages) {
            if (!messages) {
                return;
            }
            log_1.default.log('MessageManager::init D_MESSAGE_OFFLINE receive size:' + messages.length);
            var messagesObjectArray = [];
            messages.forEach(function (message) {
                var dataMessageObject = parse_data_message_1.default(message);
                messagesObjectArray.push(dataMessageObject);
            });
            if (messagesObjectArray.length > 0) {
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.DATA_MESSAGE_OFFLINE, { messages: messagesObjectArray });
            }
        });
        this.mtdx.on(ACK, function (ack) {
            switch (ack.uri) {
                case im_constant_1.default.IM.URI_IM_CANCEL_MSG_RES:
                case im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG_RES:
                case pub_constant_1.default.PUB.URI_PUB_CANCEL_MSG_RES:
                case pub_constant_1.default.PUB.URI_PUB_CANCEL_KF_MSG_RES: {
                    _this._ackCancelMessage(ack);
                    break;
                }
                default: {
                    _this._ackMessage(ack);
                }
            }
        });
        this.mtdx.on(NOTICE, function (_a) {
            var toGuid = _a.toGuid, channel = _a.channel, type = _a.type, data = _a.data;
            log_1.default.log('MessageManager::init receive group notice toGuid:' + toGuid + ' channel:' + channel + ' type:' + type);
            if (type === constant_1.GROUP_NOTICE_TYPE.DELETE) {
                if (_this.hasLocalMessages(toGuid, channel)) {
                    _this.clearMessagesInMap(toGuid, channel);
                }
            }
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.NOTICE, {
                toGuid: toGuid,
                channelId: channel,
                type: type,
                data: data,
            });
        });
        this.mtdx.on(OPPOSITE_READ, function (_a) {
            var uid = _a.uid, deviceType = _a.deviceType, syncReadItems = _a.syncReadItems;
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.OPPOSITE_READ, {
                uid: uid,
                deviceType: deviceType,
                items: syncReadItems.map(function (_a) {
                    var chatId = _a.chatId, type = _a.type, peerAppId = _a.peerAppId, channel = _a.channel, sid = _a.sid, msgIds = _a.msgIds;
                    return __assign({ chatId: chatId, type: sid ? constant_1.SESSION_TYPE.CHAT2 : constant_1.SESSION_TYPE.CHAT, peerAppId: peerAppId, channelId: channel, mids: msgIds }, (sid ? { sid: sid } : {}));
                })
            });
        });
        this.mtdx.on(OPPOSITE_READ_ACK, function (_a) {
            var msgUuid = _a.msgUuid;
            if (_this._oppositeReadMap.has(msgUuid)) {
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.OPPOSITE_READ_ACK, { uuid: msgUuid });
            }
        });
        this.mtdx.on(PUB_OPPOSITE_READ, function (_a) {
            var uid = _a.uid, oppositeUuid = _a.oppositeUuid, deviceType = _a.deviceType, syncReadItems = _a.syncReadItems;
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.PUB_OPPOSITE_READ, {
                uid: uid,
                oppositeUuid: oppositeUuid,
                deviceType: deviceType,
                items: syncReadItems.map(function (_a) {
                    var chatId = _a.chatId, peerUid = _a.peerUid, peerAppId = _a.peerAppId, type = _a.type, channel = _a.channel, sid = _a.sid, sts = _a.sts;
                    return __assign({ chatId: chatId,
                        peerUid: peerUid,
                        peerAppId: peerAppId, type: peerUid && peerUid == 0 ? (sid ? constant_1.SESSION_TYPE.PUB_CHAT2 : constant_1.SESSION_TYPE.PUB_CHAT) : (sid ? constant_1.SESSION_TYPE.CS_CHAT2 : constant_1.SESSION_TYPE.CS_CHAT), channelId: channel, sts: parseInt(sts) }, (sid ? { sid: sid } : {}));
                })
            });
        });
        this.mtdx.on(PUB_OPPOSITE_READ_ACK, function (_a) {
            var oppositeUuid = _a.oppositeUuid;
            if (_this._oppositeReadMap.has(oppositeUuid)) {
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.PUB_OPPOSITE_READ_ACK, { uuid: oppositeUuid });
            }
        });
        this.mtdx.on(RECEIPT_GROUP_MESSAGE_ACK, function (_a) {
            var _b = _a.receiptUuid, receiptUuid = _b === void 0 ? '' : _b, _c = _a.deviceType, deviceType = _c === void 0 ? 0 : _c, _d = _a.cts, cts = _d === void 0 ? '' : _d, _e = _a.items, items = _e === void 0 ? [] : _e;
            if (items && items.length > 0) {
                event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.RECEIPT_GROUP_MESSAGE, {
                    uuid: receiptUuid,
                    deviceType: deviceType,
                    cts: cts,
                    items: items.map(function (_a) {
                        var msgUuid = _a.msgUuid, toUid = _a.toUid, msgId = _a.msgId;
                        return {
                            uuid: msgUuid,
                            toUid: toUid,
                            mid: msgId,
                        };
                    }),
                });
            }
        });
        this.mtdx.on(RECEIPT_GROUP_MESSAGE, function (_a) {
            var _b = _a.receiptUuid, receiptUuid = _b === void 0 ? '' : _b, _c = _a.fromUid, fromUid = _c === void 0 ? '' : _c, _d = _a.toGuid, toGuid = _d === void 0 ? '' : _d, _e = _a.channel, channel = _e === void 0 ? 0 : _e, _f = _a.cts, cts = _f === void 0 ? '' : _f, _g = _a.deviceType, deviceType = _g === void 0 ? 0 : _g, items = _a.items;
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.RECEIPT_GROUP_MESSAGE, {
                uuid: receiptUuid,
                fromUid: fromUid,
                toGuid: toGuid,
                channelId: channel,
                cts: cts,
                deviceType: deviceType,
                items: items.map(function (_a) {
                    var msgUuid = _a.msgUuid, toUid = _a.toUid, msgId = _a.msgId;
                    return {
                        uuid: msgUuid,
                        toUid: toUid,
                        mid: msgId,
                    };
                }),
            });
        });
        this.mtdx.on(PUB_MESSAGE_ADDITION, function (datum) {
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.PUB_MESSAGE_ADDITION, _this._parseMsgAddtion(datum));
        });
        this.mtdx.on(IM_MESSAGE_ADDITION, function (datum) {
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.IM_MESSAGE_ADDITION, _this._parseMsgAddtion(datum));
        });
    };
    MessageManager.prototype.clearAllMessages = function () {
        this._messageMap = new map_1.default();
        this._localMessageMap = new map_1.default();
        this._cancelQueueMap = new map_1.default();
        this._oppositeReadMap = new map_1.default();
    };
    MessageManager.prototype.hasLocalMessageInArray = function (message) {
        var existMessages = this.getMessages(message.belongTo, message.channelId, message.sid);
        return (existMessages.filter(function (existMessage) {
            // 消息已经存在并且不是撤回消息的场景
            if (existMessage.uuid === message.uuid &&
                existMessage.mid === message.mid &&
                !(!existMessage.isCancel && message.isCancel)) {
                return true;
            }
            return false;
        }).length > 0);
    };
    MessageManager.prototype.hasLocalMessages = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
        return this._messageMap.has(sessionId);
    };
    MessageManager.prototype.getMessages = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        var messages = [];
        if (this.hasLocalMessages(uid, channelId, sid)) {
            var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
            messages = __spreadArrays(this._messageMap.get(sessionId));
        }
        return messages;
    };
    MessageManager.prototype.getMessageById = function (_a) {
        var uuid = _a.uuid, mid = _a.mid;
        var result = null;
        for (var _i = 0, _b = this._messageMap.values(); _i < _b.length; _i++) {
            var messages = _b[_i];
            if (messages == null) {
                continue;
            }
            messages.forEach(function (message) {
                if (uuid && message.uuid === uuid) {
                    result = message;
                }
                if (mid && message.mid === mid) {
                    result = message;
                }
            });
            if (result) {
                break;
            }
        }
        return result;
    };
    MessageManager.prototype.deleteMessages = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (this.hasLocalMessages(uid, channelId, sid)) {
            log_1.default.log('SessionManager::deleteMessages found local message uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
            var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
            return this._messageMap.delete(sessionId);
        }
        else {
            log_1.default.log('SessionManager::deleteMessages not found local message uid:' + uid + ' channelId:' + channelId + ' sid:' + sid);
        }
        return false;
    };
    MessageManager.prototype.deleteAllSendSuccessMessages = function () {
        for (var _i = 0, _a = this._messageMap.keys(); _i < _a.length; _i++) {
            var key = _a[_i];
            var messages = this._messageMap.get(key);
            if (!messages) {
                continue;
            }
            for (var _b = 0, messages_1 = messages; _b < messages_1.length; _b++) {
                var message = messages_1[_b];
                if (!message) {
                    continue;
                }
                if ((message.status == models_1.Message.STATUS.STATUS_ACK && (message.type && message.type != constant_1.MESSAGE_TYPE.MSG_TYPE_EVENT))
                    || (message.status == constant_1.CANCEL_STATUS.CANCELED)) {
                    // 假如是服务端存储的消息，则不处理。注意系统消息服务端是不存储的
                    continue;
                }
                this.putLocalMessageMap(message);
            }
        }
        this._messageMap = new map_1.default();
    };
    MessageManager.prototype.neatenMessage = function (uid, channelId) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        log_1.default.error('MessageManager::neatenMessage 已废弃');
    };
    MessageManager.prototype.getLastMessage = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (this.hasLocalMessages(uid, channelId, sid)) {
            var messages = this.getMessages(uid, channelId, sid);
            return messages[messages.length - 1];
        }
        return null;
    };
    MessageManager.prototype.getFirstMidMessage = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (this.hasLocalMessages(uid, channelId, sid)) {
            var messages = this.getMessages(uid, channelId, sid);
            var firstMidMessage_1 = null;
            messages.forEach(function (message) {
                // 处理增加到客户端的假消息情况
                if (!message.isLocal &&
                    (message.mid && message.mid != 0) &&
                    (!firstMidMessage_1 || (firstMidMessage_1 && message.svrTime < firstMidMessage_1.svrTime))) {
                    firstMidMessage_1 = message;
                }
            });
            return firstMidMessage_1 ? firstMidMessage_1 : null;
        }
        return null;
    };
    MessageManager.prototype.getLastMidMessage = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (this.hasLocalMessages(uid, channelId, sid)) {
            var messages = this.getMessages(uid, channelId, sid);
            var lastMidMessage_1 = messages[0];
            messages.forEach(function (message) {
                if (message.svrTime > lastMidMessage_1.svrTime) {
                    lastMidMessage_1 = message;
                }
            });
            return lastMidMessage_1;
        }
        return null;
    };
    MessageManager.prototype.hasLocalMessageMap = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        return this._localMessageMap.has(uuid);
    };
    MessageManager.prototype.getLocalMessageMap = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        if (this._localMessageMap.has(uuid)) {
            return this._localMessageMap.get(uuid);
        }
        return null;
    };
    MessageManager.prototype.putLocalMessageMap = function (message) {
        this._localMessageMap.set(message.uuid, message);
    };
    MessageManager.prototype.deleteLocalMessageMap = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        if (this._localMessageMap.has(uuid)) {
            return this._localMessageMap.delete(uuid);
        }
        return false;
    };
    MessageManager.prototype.getLocalMessages = function (uid, channelId, sid) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        var messages = [];
        if (!this._localMessageMap) {
            return messages;
        }
        var paramSessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid ? sid : '' });
        for (var _i = 0, _a = this._localMessageMap.keys(); _i < _a.length; _i++) {
            var key = _a[_i];
            var message = this._localMessageMap.get(key);
            var itemSessionId = sessionIdProcessor_1.default.create({ uid: message.belongTo, channelId: message.channelId, sid: message.sid ? message.sid : '' });
            if (paramSessionId == itemSessionId) {
                messages.push(message);
            }
        }
        return messages;
    };
    MessageManager.prototype.putCancelMessageInQueue = function (message) {
        this._cancelQueueMap.set(message.mid, message);
    };
    MessageManager.prototype.getAndDeleteCancelQueueMessage = function (mid) {
        if (mid === void 0) { mid = ''; }
        var ret = this._cancelQueueMap.get(mid);
        if (this._cancelQueueMap.has(mid)) {
            this._cancelQueueMap.delete(mid);
        }
        return ret;
    };
    MessageManager.prototype.putMessagesInMap = function (uid, channelId, sid, messages, fromSource) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (messages === void 0) { messages = []; }
        if (fromSource === void 0) { fromSource = constant_1.MESSAGE_SOURCE.ONLINE; }
        if (messages.length > 0) {
            var existMessages = this.getMessages(uid, channelId, sid);
            var mergeMap_1 = new map_1.default();
            existMessages.forEach(function (message) {
                mergeMap_1.setNoSize(message.uuid, message);
            });
            mergeMap_1.updateSize();
            messages.forEach(function (message) {
                if (!message) {
                    return;
                }
                var oldMessage = mergeMap_1.get(message.uuid);
                if (oldMessage && oldMessage.isCancel && (oldMessage.status === constant_1.CANCEL_STATUS.CANCELING || oldMessage.status === constant_1.CANCEL_STATUS.CANCELED)) {
                    // 假如有撤回中或者撤回成功消息，那么不更新内存。出现场景是：消息在撤回中，假如拉取到了历史那么会走入到这个逻辑
                    log_1.default.log('MessageManager::putMessagesInMap oldMessage is canceling uuid:' + oldMessage.uuid);
                }
                else {
                    mergeMap_1.set(message.uuid, message);
                }
            });
            this.saveMessages({ uid: uid, channelId: channelId, sid: sid, messages: this.sortMessage(mergeMap_1.values()), fromSource: fromSource, updateMessages: messages });
        }
        else {
            // 保证在没有返回历史消息时（即全部获取完）也能够触发事件
            this.saveMessages({ uid: uid, channelId: channelId, sid: sid, messages: this.getMessages(uid, channelId, sid) });
        }
    };
    MessageManager.prototype.deleteMessagesInMap = function (uid, channelId, sid, messages, fromSource, needNotice) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (messages === void 0) { messages = []; }
        if (fromSource === void 0) { fromSource = constant_1.MESSAGE_SOURCE.ONLINE; }
        if (needNotice === void 0) { needNotice = true; }
        if (messages && messages.length > 0) {
            var existMessages = this.getMessages(uid, channelId, sid);
            var mergeMap_2 = new map_1.default();
            existMessages.forEach(function (message) {
                var needDel = false;
                messages.forEach(function (delMessage) {
                    if (!delMessage) {
                        return;
                    }
                    if (delMessage.uuid == message.uuid) {
                        needDel = true;
                    }
                });
                if (!needDel) {
                    mergeMap_2.set(message.uuid, message);
                }
            });
            this.saveMessages({ uid: uid, channelId: channelId, sid: sid, messages: this.sortMessage(mergeMap_2.values()), fromSource: fromSource, updateMessages: messages, needNotice: needNotice });
        }
    };
    MessageManager.prototype.clearMessagesInMap = function (uid, channelId, sid, fromSource) {
        if (uid === void 0) { uid = ''; }
        if (channelId === void 0) { channelId = userData_1.default.get('channelId'); }
        if (fromSource === void 0) { fromSource = constant_1.MESSAGE_SOURCE.ONLINE; }
        this.saveMessages({ uid: uid, channelId: channelId, sid: sid, messages: [], fromSource: fromSource, updateMessages: this.getMessages(uid, channelId, sid) });
    };
    MessageManager.prototype.clearMessagesBySession = function (_a) {
        var _this = this;
        var _b = _a.retainCount, retainCount = _b === void 0 ? -1 : _b, _c = _a.sessionsId, sessionsId = _c === void 0 ? [] : _c, _d = _a.needNotice, needNotice = _d === void 0 ? true : _d;
        if (retainCount < 0 || !sessionsId) {
            return;
        }
        sessionsId.forEach(function (element) {
            if (!element) {
                return;
            }
            var existMessages = _this.getMessages(element.uid, element.channelId, element.sid);
            var needDelCount = existMessages.length - retainCount > 0 ? existMessages.length - retainCount : 0;
            if (needDelCount > 0) {
                var needDelMessages = [];
                for (var i = 0; i < needDelCount; i++) {
                    needDelMessages.push(existMessages[i]);
                }
                if (needDelMessages.length > 0) {
                    _this.deleteMessagesInMap(element.uid, element.channelId, element.sid, needDelMessages);
                }
            }
        });
    };
    MessageManager.prototype.putCancelMessageInMap = function (message) {
        var belongTo = message.belongTo, channelId = message.channelId, sid = message.sid;
        var messages = this.getMessages(belongTo, channelId, sid);
        var index = -1;
        for (var i = 0; i < messages.length; i++) {
            var element = messages[i];
            if (element.mid === message.mid) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            if (message.isCancel) {
                var dealMessage = messages[index];
                if (!dealMessage.isCancel) { // 假如内存中存在原始消息，则将原始消息放入撤回消息的字段中
                    message.originMessage = dealMessage;
                }
                else if (dealMessage.originMessage) {
                    message.originMessage = dealMessage.originMessage;
                }
            }
            messages[index] = message;
        }
        this.saveMessages({ uid: belongTo, channelId: channelId, sid: sid, messages: messages, needNotice: true, fromSource: constant_1.MESSAGE_SOURCE.ONLINE, updateMessages: [message] });
    };
    MessageManager.prototype.sendMessageCheckLen = function (messageDatum) {
        var binaryMessageCheckLen = create_message_1.default(__assign(__assign({}, messageDatum), { from: config_manager_1.default.getConfig().uid }));
        var len = binaryMessageCheckLen.getBytes().byteLength;
        if (len > 32767) {
            var MaxLenOver = {
                code: 1,
                len: len
            };
            throw new Error(JSON.stringify(MaxLenOver));
            return false;
        }
        return true;
    };
    /**
     * @param to 消息接收方uid
     * @param fromName 消息发送者名称
     * @param sessionType 消息所属会话类型
     * @param toAppId 接收消息业务方appId
     * @param channelId 接受消息业务方ChannelId
     * @param extension 消息扩展字段
     * @param body 消息内包内容
     * @returns 返回消息体
     * @memberof MessageManager
     */
    MessageManager.prototype.sendMessage = function (messageDatum) {
        var _this = this;
        if (!this.sendMessageCheckLen(messageDatum)) {
            return null;
        }
        var uuid = messageDatum.uuid;
        var binaryMessage = create_message_1.default(__assign(__assign({}, messageDatum), { from: config_manager_1.default.getConfig().uid }));
        if (uuid) {
            binaryMessage.msgUuid = uuid;
        }
        switch (messageDatum.sessionType) {
            case models_1.Session.TYPE.CHAT:
            case models_1.Session.TYPE.CHAT2:
            case models_1.Session.TYPE.GROUP_CHAT: {
                this.mtdx.imSDK.send(binaryMessage);
                break;
            }
            case models_1.Session.TYPE.PUB_CHAT:
            case models_1.Session.TYPE.PUB_CHAT2:
            case models_1.Session.TYPE.CS_CHAT2:
            case models_1.Session.TYPE.CS_CHAT: {
                this.mtdx.pubSDK.send(binaryMessage);
                break;
            }
        }
        var message = parse_message_1.default(__assign(__assign({}, binaryMessage), { status: models_1.Message.STATUS.STATUS_SENT }));
        log_1.default.log('MessageManager::sendMessage message info:' + message);
        this.putLocalMessageMap(message);
        this.putMessagesInMap(message.belongTo, message.channelId, message.sid, [message]);
        message_report_1.default.reportMessageStart(message);
        setTimeout(function () {
            _this.checkSentMessageStatus(message.uuid);
        }, this.getSendMessageTimeoutTime());
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message });
        return message;
    };
    MessageManager.prototype.getSendMessageTimeoutTime = function () {
        var timeoutTime = userData_1.default.get('sendMessageTimeoutTime');
        return timeoutTime && timeoutTime > 0 ? timeoutTime : MESSAGE_TIMEOUT_TIME;
    };
    MessageManager.prototype.createMessage = function (messageDatum) {
        return parse_message_1.default(messageDatum);
    };
    MessageManager.prototype.sendPubTTMessage = function (messageDatum) {
        var binaryMessage = create_pub_tt_message_1.default(__assign(__assign({}, messageDatum), { from: config_manager_1.default.getConfig().uid }));
        this.mtdx.pubSDK.send(binaryMessage);
        var retMessageObject = parse_message_1.default(binaryMessage);
        log_1.default.log('MessageManager::sendPubTTMessage message info:' + retMessageObject);
        return retMessageObject;
    };
    MessageManager.prototype.sendCancelMessage = function (messageDatum) {
        var _this = this;
        var binaryMessage = create_cancel_message_1.default(__assign(__assign({}, messageDatum), { from: config_manager_1.default.getConfig().uid }));
        switch (messageDatum.sessionType) {
            case models_1.Session.TYPE.CHAT:
            case models_1.Session.TYPE.CHAT2:
            case models_1.Session.TYPE.GROUP_CHAT: {
                this.mtdx.imSDK.send(binaryMessage);
                break;
            }
            case models_1.Session.TYPE.PUB_CHAT:
            case models_1.Session.TYPE.PUB_CHAT2:
            case models_1.Session.TYPE.CS_CHAT2:
            case models_1.Session.TYPE.CS_CHAT: {
                this.mtdx.pubSDK.send(binaryMessage);
                break;
            }
        }
        var message = parse_message_1.default(binaryMessage);
        message.status = constant_1.CANCEL_STATUS.CANCELING;
        // 假如存在原始消息，则需要赋值过去，假如不这么做的话连续调用两次sendCancelMessage会导致原始消息丢失
        var messageOld = this.getLocalMessageMap(message.uuid);
        if (messageOld && messageOld.originMessage) {
            message.originMessage = messageOld.originMessage;
            this.deleteLocalMessageMap(message.uuid);
        }
        log_1.default.log('MessageManager::sendCancelMessage message info:' + message);
        this.putCancelMessageInQueue(message);
        this.putCancelMessageInMap(message);
        setTimeout(function () {
            _this.checkSentCancelMessageStatus(message.mid);
        }, this.getSendMessageTimeoutTime());
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message });
        return message;
    };
    /**
     * @param messageDatum 消息体
     * @param isCountUnread 插入本地消息是否计算未读数
     * @returns 没有返回值
     * @memberof MessageManager
     */
    MessageManager.prototype.addFakeMessage = function (messageDatum) {
        var binaryMessage = create_message_1.default(messageDatum);
        var message = parse_message_1.default(__assign(__assign({}, binaryMessage), { status: models_1.Message.STATUS.STATUS_ACK, isLocal: true }));
        log_1.default.log('MessageManager::addFakeMessage message info:' + message);
        // 本地消息也会根据未读数计算策略来计算未读数
        if (typeof messageDatum.time !== 'undefined') { // 假如外部有传入时间，则使用外部的时间
            message.time = messageDatum.time;
        }
        message.svrTime = message.time;
        if (this.hasLocalMessageMap(message.uuid)) {
            log_1.default.error('MessageManager::addFakeMessage message exist uuid:' + message.uuid);
            return this.getLocalMessageMap(message.uuid);
        }
        this.putLocalMessageMap(message);
        this.putMessagesInMap(message.belongTo, message.channelId, message.sid, [message], constant_1.MESSAGE_SOURCE.LOCAL);
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.ADD_FAKE_MESSAGE, { message: message });
        return message;
    };
    MessageManager.prototype.getFakeMessage = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        return this.getLocalMessageMap(uuid);
    };
    MessageManager.prototype.modifyFakeMessage = function (message) {
        if (!message || !message.uuid || !this.hasLocalMessageMap(message.uuid)) {
            return;
        }
        this.putLocalMessageMap(message);
        this.putMessagesInMap(message.belongTo, message.channelId, message.sid, [message], constant_1.MESSAGE_SOURCE.LOCAL);
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MODIFY_FAKE_MESSAGE, { message: message });
    };
    MessageManager.prototype.deleteFakeMessage = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        var message = this.getFakeMessage(uuid);
        if (!message || !message.uuid) {
            return;
        }
        this.deleteLocalMessageMap(message.uuid);
        this.deleteMessagesInMap(message.belongTo, message.channelId, message.sid, [message], constant_1.MESSAGE_SOURCE.LOCAL);
        event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.DELETE_FAKE_MESSAGE, { message: message });
    };
    MessageManager.prototype.checkSentMessageStatus = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        if (!this.hasLocalMessageMap(uuid)) {
            return;
        }
        var message = this.getLocalMessageMap(uuid);
        message.status = models_1.Message.STATUS.STATUS_TIMEOUT;
        log_1.default.log('MessageManager::checkSentMessageStatus timeout message info:' + message);
        this.putLocalMessageMap(message);
        this.putMessagesInMap(message.belongTo, message.channel, message.sid, [message]);
        message_report_1.default.reportMessageEnd(message);
    };
    MessageManager.prototype.checkSentCancelMessageStatus = function (mid) {
        if (mid === void 0) { mid = ''; }
        var message = this.getAndDeleteCancelQueueMessage(mid);
        if (!message) {
            return;
        }
        message.status = models_1.Message.STATUS.STATUS_TIMEOUT;
        log_1.default.log('MessageManager::checkSentCancelMessageStatus timeout message info:' + message);
        this.putLocalMessageMap(message);
        this.putCancelMessageInMap(message);
    };
    MessageManager.prototype.resendMessage = function (uuid) {
        if (uuid === void 0) { uuid = ''; }
        var message = this.getLocalMessageMap(uuid);
        if (message) {
            log_1.default.log('MessageManager::resendMessage msgUuid:' + uuid);
            this.deleteLocalMessageMap(uuid);
            return this.sendMessage(message);
        }
        else {
            log_1.default.log('MessageManager::resendMessage not found message msgUuid:' + uuid);
        }
        return false;
    };
    MessageManager.prototype.saveMessages = function (_a) {
        var uid = _a.uid, _b = _a.channelId, channelId = _b === void 0 ? userData_1.default.get('channelId') : _b, _c = _a.sid, sid = _c === void 0 ? undefined : _c, _d = _a.messages, messages = _d === void 0 ? [] : _d, _e = _a.needNotice, needNotice = _e === void 0 ? true : _e, _f = _a.fromSource, fromSource = _f === void 0 ? constant_1.MESSAGE_SOURCE.ONLINE : _f, _g = _a.updateMessages, updateMessages = _g === void 0 ? [] : _g;
        var sessionId = sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid });
        this._messageMap.set(sessionId, messages);
        if (messages.length > 0 && needNotice) {
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.UPDATE_MESSAGES, { uid: uid, channelId: channelId, sid: sid, messages: messages, fromSource: fromSource, updateMessages: updateMessages });
        }
    };
    MessageManager.prototype.sortMessage = function (messages) {
        if (messages === void 0) { messages = []; }
        if (messages.length > 0) {
            return messageSorter_1.default.sort(messages);
        }
        return [];
    };
    MessageManager.prototype._ackMessage = function (_a) {
        var rescode = _a.rescode, msgUuid = _a.msgUuid, msgId = _a.msgId, cts = _a.cts, seqId = _a.seqId;
        var message = this.getLocalMessageMap(msgUuid);
        if (!message) {
            return;
        }
        // 可能受到重复的ACK，或者是通过短连接更新消息内容后，收到长连接的ACK
        message.sendCode = rescode;
        if (message) {
            switch (rescode) {
                case 0: {
                    message.status = models_1.Message.STATUS.STATUS_ACK;
                    break;
                }
                default: {
                    message.status = models_1.Message.STATUS.STATUS_SEND_ERR;
                }
            }
            if (seqId) {
                if (message.setSeqId) {
                    message.setSeqId(seqId);
                }
                else {
                    log_1.default.error('MessageManager::sendMessage error not setSeqId message:' + message);
                }
            }
            if (msgId && msgId !== '0') {
                message.setMid(msgId);
            }
            log_1.default.log('MessageManager::sendMessage result rescode:' + rescode + ' message info:' + message);
            this.deleteLocalMessageMap(msgUuid);
            this.putMessagesInMap(message.belongTo, message.channelId, message.sid, [message]);
            message_report_1.default.reportMessageEnd(message);
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message }, true);
        }
        else {
            log_1.default.log('MessageManager::sendMessage result not found message msgUuid:' + msgUuid + ' msgId:' + msgId);
        }
    };
    MessageManager.prototype._ackCancelMessage = function (_a) {
        var rescode = _a.rescode, msgId = _a.msgId;
        var mid = msgId.value();
        var message = this.getAndDeleteCancelQueueMessage(mid);
        if (!message) {
            return;
        }
        message.sendCode = rescode;
        if (rescode === 0) {
            log_1.default.log("MessageManager::_ackCancelMessage success rescode:" + rescode + ' message info:' + message);
            message.status = constant_1.CANCEL_STATUS.CANCELED;
            this.putCancelMessageInMap(message);
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message }, true);
        }
        else {
            log_1.default.log("MessageManager::_ackCancelMessage fail rescode:" + rescode + ' message info:' + message);
            message.status = constant_1.CANCEL_STATUS.CANCELERROR;
            this.putCancelMessageInMap(message);
            event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.MESSAGE, { message: message }, true);
        }
    };
    MessageManager.prototype.fetchHistoryMessagesByOrder = function (_a) {
        var uid = _a.uid, type = _a.type, channelId = _a.channelId, _b = _a.limit, limit = _b === void 0 ? 20 : _b, sid = _a.sid, _c = _a.st, st = _c === void 0 ? 0 : _c;
        var firstMessage = this.getFirstMidMessage(uid, channelId, sid);
        log_1.default.log('MessageManager::fetchHistoryMessagesByOrder uid:' + uid + ' type:' + type
            + ' channelId:' + channelId + ' limit:' + limit + ' sid:' + sid
            + ' firstMessage:' + firstMessage);
        return this.fetchHistoryMessages({ uid: uid, type: type, channelId: channelId, mid: firstMessage ? firstMessage.mid : BIG_MID, limit: limit, sid: sid, st: st });
    };
    MessageManager.prototype.fetchHistoryMessagesByTimeOnly = function (_a) {
        var _b = _a.uid, uid = _b === void 0 ? '' : _b, _c = _a.type, type = _c === void 0 ? constant_1.SESSION_TYPE.CHAT : _c, _d = _a.channelId, channelId = _d === void 0 ? 0 : _d, sid = _a.sid, _e = _a.startTime, startTime = _e === void 0 ? 0 : _e, _f = _a.endTime, endTime = _f === void 0 ? Date.now() : _f, _g = _a.limit, limit = _g === void 0 ? 20 : _g;
        var sessionDataArrayItem = {};
        switch (type) {
            case constant_1.SESSION_TYPE.CHAT: {
                sessionDataArrayItem = {
                    b: uid,
                    ai: userData_1.default.get('appId'),
                    chid: channelId,
                    st: startTime,
                    et: endTime,
                    g: 0,
                };
                break;
            }
            case constant_1.SESSION_TYPE.CHAT2: {
                sessionDataArrayItem = {
                    b: uid,
                    ai: userData_1.default.get('appId'),
                    chid: channelId,
                    st: startTime,
                    et: endTime,
                    g: 0,
                    sid: sid
                };
                break;
            }
            case constant_1.SESSION_TYPE.GROUP_CHAT: {
                sessionDataArrayItem = {
                    b: uid,
                    ai: userData_1.default.get('appId'),
                    chid: channelId,
                    st: startTime,
                    et: endTime,
                    g: 1,
                };
                break;
            }
            case constant_1.SESSION_TYPE.PUB_CHAT: {
                sessionDataArrayItem = {
                    u: uid,
                    st: startTime,
                    et: endTime,
                };
                break;
            }
            case constant_1.SESSION_TYPE.PUB_CHAT2: {
                sessionDataArrayItem = {
                    u: uid,
                    st: startTime,
                    et: endTime,
                    sid: sid
                };
                break;
            }
            case constant_1.SESSION_TYPE.CS_CHAT: {
                var _h = uid.split('_'), pubId = _h[0], peerUid = _h[1];
                sessionDataArrayItem = {
                    u: pubId,
                    pu: peerUid,
                    st: startTime,
                    et: endTime,
                };
                break;
            }
            case constant_1.SESSION_TYPE.CS_CHAT2: {
                var _j = uid.split('_'), pubId = _j[0], peerUid = _j[1];
                sessionDataArrayItem = {
                    u: pubId,
                    pu: peerUid,
                    st: startTime,
                    et: endTime,
                    sid: sid
                };
                break;
            }
        }
        var paramObject = {
            type: type,
            limit: limit,
            sessionDataArray: [sessionDataArrayItem],
            shouldUpdateMessageMap: false,
        };
        log_1.default.log('MessageManager::fetchHistoryMessagesByTimeOnly info:' + JSON.stringify(paramObject));
        return this.fetchMultiSessionsHistoryMessagesByTimeRange(paramObject).then(function (res) {
            return {
                messages: res[sessionIdProcessor_1.default.create({ uid: uid, channelId: channelId, sid: sid })]
            };
        });
    };
    MessageManager.prototype.fetchHistoryMessages = function (_a) {
        var _this = this;
        var uid = _a.uid, type = _a.type, channelId = _a.channelId, _b = _a.mid, mid = _b === void 0 ? BIG_MID : _b, _c = _a.limit, limit = _c === void 0 ? 20 : _c, sid = _a.sid, _d = _a.st, st = _d === void 0 ? 0 : _d, _e = _a.shouldUpdateMessageMap, shouldUpdateMessageMap = _e === void 0 ? true : _e, _f = _a.shouldUpdateMessageMapNotify, shouldUpdateMessageMapNotify = _f === void 0 ? true : _f;
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('MessageManager::fetchHistoryMessages uid:' + uid + ' type:' + type
                + ' channelId:' + channelId + ' limit:' + limit + ' sid:' + sid
                + ' mid:' + mid);
            var appId = config_manager_1.default.getConfig().appId;
            var options = {
                data: {
                    lm: limit,
                    ai: appId,
                    od: 0,
                    pl: 1,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0) {
                        log_1.default.error('MessageManager::fetchHistoryMessages fail rescode:' + rescode
                            + ' message:' + (data ? data.message : ''));
                        return reject({ code: rescode, message: data.message });
                    }
                    var parseMessages = _this.parseHistoryRes(data.res);
                    log_1.default.log('MessageManager::fetchHistoryMessages suc next:' + data.next + ' messages:' + message_util_1.default.getMessageArrayPrint(parseMessages));
                    resolve({ msgs: parseMessages, next: data.next });
                },
                error: function (xhr, status, err) {
                    log_1.default.error('MessageManager::fetchHistoryMessages fail xhr:' + xhr + ' status:' + status + ' err:' + err);
                    return reject({ code: constant_2.SDKRESCODE.UNKNOWN_ERROR, message: 'xhr:' + xhr + ' status:' + status + ' err:' + err });
                },
            };
            switch (type) {
                case constant_1.SESSION_TYPE.CHAT: {
                    options.data.bs = [{ b: uid, ai: appId, g: 0, chid: channelId, msgidS: 0, msgidB: mid, st: st }];
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CHAT2: {
                    options.data.bs = [{ b: uid, ai: appId, g: 0, chid: channelId, msgidS: 0, msgidB: mid, sid: sid, st: st }];
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.GROUP_CHAT: {
                    options.data.bs = [{ b: uid, ai: appId, g: 1, chid: channelId, msgidS: 0, msgidB: mid, st: st }];
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT: {
                    options.data.ps = [{ u: uid, pu: 0, chid: channelId, msgidS: 0, msgidB: mid, st: st }];
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT2: {
                    options.data.ps = [{ u: uid, pu: 0, chid: channelId, msgidS: 0, msgidB: mid, sid: sid, st: st }];
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT: {
                    var _a = uid.split('_'), pubId = _a[0], peerUid = _a[1];
                    options.data.ps = [{ u: pubId, pu: peerUid, chid: channelId, msgidS: 0, msgidB: mid, st: st }];
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT2: {
                    var _b = uid.split('_'), pubId = _b[0], peerUid = _b[1];
                    options.data.ps = [{ u: pubId, pu: peerUid, chid: channelId, msgidS: 0, msgidB: mid, sid: sid, st: st }];
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
            }
        }).then(function (res) {
            if (shouldUpdateMessageMap && shouldUpdateMessageMapNotify) {
                var msgs = _this.mergeLocalMessage(uid, channelId, sid, res.msgs, res.next > 0, true, mid);
                _this.putMessagesInMap(uid, channelId, sid, msgs, constant_1.MESSAGE_SOURCE.HISTORY);
            }
            return res;
        });
    };
    MessageManager.prototype.fetchLatterMessages = function (_a) {
        var _this = this;
        var uid = _a.uid, type = _a.type, channelId = _a.channelId, _b = _a.mid, mid = _b === void 0 ? BIG_MID : _b, _c = _a.limit, limit = _c === void 0 ? 20 : _c, _d = _a.shouldUpdateMessageMap, shouldUpdateMessageMap = _d === void 0 ? true : _d, _e = _a.shouldUpdateMessageMapNotify, shouldUpdateMessageMapNotify = _e === void 0 ? true : _e, _f = _a.peerAppId, peerAppId = _f === void 0 ? 0 : _f;
        return new promise_1.default(function (resolve, reject) {
            var appId = config_manager_1.default.getConfig().appId;
            var options = {
                data: {
                    lm: limit,
                    ai: appId,
                    pl: 1,
                    od: 0
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0) {
                        log_1.default.error('MessageManager::fetchLatterMessages fail rescode:' + rescode
                            + ' message:' + (data ? data.message : ''));
                        return reject({ code: rescode, message: data.message });
                    }
                    var parseMessages = _this.parseHistoryRes(data.res);
                    log_1.default.log('MessageManager::fetchLatterMessages suc next:' + data.next + ' messages:' + message_util_1.default.getMessageArrayPrint(parseMessages));
                    resolve({ msgs: parseMessages, next: data.next });
                },
                error: function (xhr, status, err) {
                    log_1.default.error('MessageManager::fetchLatterMessages fail xhr:' + xhr + ' status:' + status + ' err:' + err);
                    return reject({ code: constant_2.SDKRESCODE.UNKNOWN_ERROR, message: 'xhr:' + xhr + ' status:' + status + ' err:' + err });
                },
            };
            switch (type) {
                case constant_1.SESSION_TYPE.CHAT:
                case constant_1.SESSION_TYPE.CHAT2:
                case constant_1.SESSION_TYPE.GROUP_CHAT: {
                    var bs = [{ b: uid, chid: channelId, msgidS: mid, g: type === constant_1.SESSION_TYPE.GROUP_CHAT ? 1 : 0, ai: peerAppId && peerAppId > 0 ? peerAppId : appId }];
                    log_1.default.log('MessageManager::fetchLatterMessages info:' + JSON.stringify(bs));
                    options.data.bs = bs;
                    _this.mtdx.HTTP.Msg.historyReverseOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT2:
                case constant_1.SESSION_TYPE.CS_CHAT: {
                    var _a = uid.split('_'), pubId = _a[0], peerUid = _a[1];
                    var ps = [{ u: pubId, pu: peerUid, chid: channelId, msgidS: mid, ai: peerAppId && peerAppId > 0 ? peerAppId : appId }];
                    log_1.default.log('MessageManager::fetchLatterMessages info:' + JSON.stringify(ps));
                    options.data.ps = ps;
                    _this.mtdx.HTTP.Pub.historyReverseOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT2:
                case constant_1.SESSION_TYPE.PUB_CHAT: {
                    var ps = [{ u: uid, pu: 0, chid: channelId, msgidS: mid, ai: peerAppId && peerAppId > 0 ? peerAppId : appId }];
                    log_1.default.log('MessageManager::fetchLatterMessages info:' + JSON.stringify(ps));
                    options.data.ps = ps;
                    _this.mtdx.HTTP.Pub.historyReverseOfChannelByRange(options);
                    break;
                }
            }
        }).then(function (res) {
            if (shouldUpdateMessageMap && shouldUpdateMessageMapNotify) {
                var msgs = _this.mergeLocalMessage(uid, channelId, '', res.msgs, res.next > 0, false, mid);
                _this.putMessagesInMap(uid, channelId, '', msgs, constant_1.MESSAGE_SOURCE.HISTORY);
            }
            return res;
        });
    };
    MessageManager.prototype.mergeLocalMessage = function (uid, channelId, sid, messages, hasMoreMessage, bUpLoad, requestMid) {
        var ret = messages ? messages : [];
        try {
            var localMessages = this.getLocalMessages(uid, channelId, sid);
            if (!localMessages || localMessages.length <= 0) {
                return ret;
            }
            var begin_1 = 0;
            var end_1 = 0;
            if (hasMoreMessage) {
                if (messages.length > 1) {
                    if (messages[0].time < messages[messages.length - 1].time) {
                        begin_1 = messages[0].time;
                        end_1 = messages[messages.length - 1].time;
                    }
                    else {
                        begin_1 = messages[messages.length - 1].time;
                        end_1 = messages[0];
                    }
                }
                else {
                    log_1.default.error('MessageManager::mergeLocalMessage messages.length:' + messages.length);
                    begin_1 = 0;
                    end_1 = -1;
                }
            }
            else {
                if (bUpLoad) {
                    if (messages && messages.length > 0) {
                        begin_1 = 0;
                        if (messages[0].time < messages[messages.length - 1].time) {
                            end_1 = messages[0].time;
                        }
                        else {
                            end_1 = messages[messages.length - 1].time;
                        }
                    }
                    else {
                        var allMessages = this.getMessages(uid, channelId.sid);
                        if (allMessages && allMessages.length > 0) {
                            if (allMessages[0].time < allMessages[allMessages.length - 1].time) {
                                end_1 = allMessages[0].time;
                            }
                            else {
                                end_1 = allMessages[allMessages.length - 1].time;
                            }
                            begin_1 = 0;
                        }
                        else {
                            begin_1 = 0;
                            end_1 = Number.MAX_VALUE;
                        }
                    }
                }
                else {
                    if (messages && messages.length > 0) {
                        if (messages[0].time < messages[messages.length - 1].time) {
                            begin_1 = messages[messages.length - 1].time;
                        }
                        else {
                            begin_1 = messages[0].time;
                        }
                        end_1 = Number.MAX_VALUE;
                    }
                    else {
                        var allMessages = this.getMessages(uid, channelId.sid);
                        if (allMessages && allMessages.length > 0) {
                            if (allMessages[0].time < allMessages[allMessages.length - 1].time) {
                                begin_1 = allMessages[allMessages.length - 1].time;
                            }
                            else {
                                begin_1 = allMessages[0].time;
                            }
                            end_1 = Number.MAX_VALUE;
                        }
                        else {
                            begin_1 = 0;
                            end_1 = Number.MAX_VALUE;
                        }
                    }
                }
            }
            if (requestMid == BIG_MID) {
                end_1 = Number.MAX_VALUE;
            }
            localMessages.forEach(function (message) {
                if (!message) {
                    return;
                }
                if (message.time >= begin_1 && message.time <= end_1) {
                    ret.push(message);
                }
            });
            return ret;
        }
        catch (error) {
            log_1.default.error('MessageManager::mergeLocalMessage messages.length:' + messages.length);
        }
        return ret;
    };
    MessageManager.prototype.parseHistoryRes = function (historyResponseArray) {
        var msgArray = [];
        try {
            historyResponseArray.forEach(function (historyRes) {
                historyRes.msgs.forEach(function (messageDatum) {
                    if (messageDatum.type !== -1 && messageDatum.msgId) {
                        var messageObject = parse_message_1.default(__assign(__assign({}, messageDatum), { status: models_1.Message.STATUS.STATUS_ACK }));
                        msgArray.push(messageObject);
                    }
                    else {
                        log_1.default.error('MessageManager::parseHistoryRes not parse message type:' + messageDatum.type + ' msgId:' + messageDatum.msgId);
                    }
                });
            });
        }
        catch (error) {
            log_1.default.error('MessageManager::parseHistoryRes error info:' + error);
        }
        return msgArray;
    };
    MessageManager.prototype._parseIMRemoteMsgs = function (data) {
        var messages = [];
        try {
            if (data) {
                data.forEach(function (res) {
                    if (res.msgs) {
                        res.msgs.forEach(function (messageDatum) {
                            if (messageDatum.type !== -1 && messageDatum.msgId) {
                                var messageObject = parse_message_1.default(__assign(__assign({}, messageDatum), { status: models_1.Message.STATUS.STATUS_ACK }));
                                messages.push(messageObject);
                            }
                            else {
                                log_1.default.error('MessageManager::_parseIMRemoteMsgs not parse message type:' + messageDatum.type + ' msgId:' + messageDatum.msgId);
                            }
                        });
                    }
                });
            }
        }
        catch (error) {
            log_1.default.error('MessageManager::_parseIMRemoteMsgs error info:' + error);
        }
        return messages;
    };
    MessageManager.prototype._parsePubRemoteMsgs = function (data) {
        var messages = [];
        try {
            if (data) {
                data.forEach(function (res) {
                    if (res.msgs) {
                        res.msgs.forEach(function (messageDatum) {
                            if (messageDatum.type !== -1 && messageDatum.msgId) {
                                var messageObject = parse_message_1.default(__assign(__assign({}, messageDatum), { status: models_1.Message.STATUS.STATUS_ACK }));
                                messages.push(messageObject);
                            }
                            else {
                                log_1.default.error('MessageManager::_parsePubRemoteMsgs not parse message type:' + messageDatum.type + ' msgId:' + messageDatum.msgId);
                            }
                        });
                    }
                });
            }
        }
        catch (error) {
            log_1.default.error('MessageManager::_parsePubRemoteMsgs error info:' + error);
        }
        return messages;
    };
    MessageManager.prototype.sendOppositeRead = function (_a) {
        var uid = _a.uid, _b = _a.type, type = _b === void 0 ? models_1.Session.TYPE.CHAT : _b, peerAppId = _a.peerAppId, channelId = _a.channelId, sid = _a.sid, _c = _a.mids, mids = _c === void 0 ? [] : _c;
        if (!uid || mids == null || mids.length <= 0) {
            return;
        }
        var binaryMessage = opposite_read_creator_1.default.createChatOppositeRead({
            myUid: config_manager_1.default.getConfig().uid,
            data: {
                uid: uid,
                // 单聊为1
                type: 1,
                peerAppId: peerAppId,
                channelId: channelId,
                mids: mids,
                sid: sid
            }
        });
        this.mtdx.imSDK.send(binaryMessage);
        this._oppositeReadMap.set(binaryMessage.msgUuid, true);
        return binaryMessage;
    };
    MessageManager.prototype.getOppositeConfig = function (_a) {
        var _this = this;
        var tenant = _a.tenant;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getOppositeConfig({
                data: {
                    tenant: tenant,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.getBothOppositeUnreadMsg = function (_a) {
        var _this = this;
        var buddy = _a.buddy, channelId = _a.channelId, sid = _a.sid, _b = _a.svid, svid = _b === void 0 ? 401 : _b, _c = _a.smsgids, smsgids = _c === void 0 ? [] : _c, _d = _a.bmsgids, bmsgids = _d === void 0 ? [] : _d;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getBothOppositeUnreadMsg({
                data: __assign({ buddy: buddy, channel: channelId, svid: svid,
                    smsgids: smsgids,
                    bmsgids: bmsgids }, (sid ? { sid: sid } : {})),
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        resolve({
                            selfUnread: data.selfUnreadStr,
                            oppoUnread: data.oppoUnreadStr,
                        });
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.getChannelBothOppositeUnreadMsg = function (_a) {
        var _this = this;
        var buddy = _a.buddy, channelId = _a.channelId, _b = _a.svid, svid = _b === void 0 ? 401 : _b, _c = _a.smsgids, smsgids = _c === void 0 ? [] : _c, _d = _a.bmsgids, bmsgids = _d === void 0 ? [] : _d, sid = _a.sid;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getChannelBothOppositeUnreadMsg({
                data: __assign({ buddy: buddy, channel: channelId, svid: svid,
                    smsgids: smsgids,
                    bmsgids: bmsgids }, (sid ? { sid: sid } : {})),
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.sendPubOppositeRead = function (_a) {
        var _b = _a.uid, uid = _b === void 0 ? '0' : _b, _c = _a.peerUid, peerUid = _c === void 0 ? '0' : _c, _d = _a.type, type = _d === void 0 ? models_1.Session.TYPE.PUB_CHAT : _d, _e = _a.peerAppId, peerAppId = _e === void 0 ? 0 : _e, _f = _a.channelId, channelId = _f === void 0 ? 0 : _f, sid = _a.sid, _g = _a.sts, sts = _g === void 0 ? 0 : _g;
        if (!uid) {
            return;
        }
        var binaryMessage = opposite_read_creator_1.default.createPubOppositeRead({
            myUid: config_manager_1.default.getConfig().uid,
            data: {
                uid: uid,
                peerUid: peerUid,
                // PUB公众号侧为1，PUB客服侧为2
                type: (type === models_1.Session.TYPE.PUB_CHAT || type === models_1.Session.TYPE.PUB_CHAT2) ? 1 : 2,
                peerAppId: peerAppId,
                channelId: channelId,
                sts: sts,
                sid: sid,
            }
        });
        this.mtdx.pubSDK.send(binaryMessage);
        this._oppositeReadMap.set(binaryMessage.oppositeUuid, true);
        return binaryMessage;
    };
    MessageManager.prototype.getPubOppositeConfig = function () {
        var _this = this;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Pub.getOppositeConfig({
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    reject(e);
                },
            });
        });
    };
    /**
     * 获取PUB对端已读时间（PUB单聊和PUB客服都可以使用此接口）
     *
     * @param {*} {chatIds = [], channelId = 0, startTime} start参数优先级高于chatIds，传入startTime参数后，获取从startTime之后所有会话的对端已读时间；传入chatIds则使用会话id来获取。
     * @returns
     * @memberof MessageManager
     */
    MessageManager.prototype.getPubOppositeReadTime = function (_a) {
        var _this = this;
        var _b = _a.chatIds, chatIds = _b === void 0 ? [] : _b, _c = _a.channelId, channelId = _c === void 0 ? 0 : _c, startTime = _a.startTime, sid = _a.sid;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Pub.getOppositeReadTime({
                data: __assign({ 
                    // 如果PUB单聊（公众号会话）没有填写peerUid字段，需要补'0'
                    chatIds: chatIds
                        .map(function (element) {
                        if (element.chatId && !element.peerUid) {
                            return {
                                chatId: element.chatId,
                                peerUid: '0',
                            };
                        }
                        return element;
                    })
                        .filter(function (element) {
                        return element.chatId && element.peerUid;
                    }), channelId: channelId,
                    startTime: startTime }, (sid ? { sid: sid } : {})),
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.getPubMessageAdditionConfig = function () {
        var _this = this;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Pub.getMessageAdditionConfig({
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    log_1.default.log('MessageManager::getPubMessageAdditionConfig success rescode:' + rescode + ' data:' + data);
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    log_1.default.error('MessageManager::getPubMessageAdditionConfig fail info:' + e);
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.fetchPubMessageAddition = function (_a) {
        var _this = this;
        var _b = _a.mids, mids = _b === void 0 ? [] : _b, _c = _a.channelId, channelId = _c === void 0 ? userData_1.default.get('channelId') : _c;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Pub.getPubMessageAddition({
                data: {
                    additions: mids
                        .map(function (element) {
                        return {
                            mid: element
                        };
                    }),
                    chid: channelId,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0 || !data) {
                        log_1.default.error('MessageManager::fetchPubMessageAddition fail rescode:' + rescode);
                        return reject({ code: rescode });
                    }
                    log_1.default.log('MessageManager::fetchPubMessageAddition suc size:' + (data.additions ? data.additions.length : 0));
                    var parseMsgAddtions = _this._parseMsgAddtionRes(data.additions);
                    resolve({ msgAddtions: parseMsgAddtions });
                },
                error: function (e) {
                    log_1.default.error('MessageManager::fetchPubMessageAddition fail info:' + e);
                    return reject(e);
                },
            });
        });
    };
    MessageManager.prototype._parseMsgAddtionRes = function (inputArray) {
        var _this = this;
        var retArray = [];
        try {
            if (inputArray) {
                inputArray.forEach(function (datum) {
                    var parseObject = _this._parseMsgAddtion(datum);
                    if (parseObject) {
                        retArray.push(parseObject);
                    }
                    else {
                        log_1.default.error('MessageManager::parseMsgAddtionRes error info:' + datum);
                    }
                });
            }
        }
        catch (error) {
            log_1.default.error('MessageManager::parseMsgAddtionRes error info:' + error);
        }
        return retArray;
    };
    MessageManager.prototype._parseMsgAddtion = function (datum) {
        try {
            if (!datum) {
                return null;
            }
            return {
                msgUuid: datum.msgUuid,
                fromUid: datum.fromUid,
                deviceType: datum.deviceType,
                deviceId: datum.deviceId,
                msgId: datum.msgId,
                channel: datum.channel,
                additionData: datum.additionData,
                receivers: datum.receivers ? datum.receivers : null,
                receiverAppId: datum.receiverAppId ? datum.receiverAppId : null,
                guid: datum.guid ? datum.guid : null,
                sts: datum.sts,
                seqId: datum.seqId,
                allowAddition: datum.allowAddition,
            };
        }
        catch (error) {
            log_1.default.error('MessageManager::parseMsgAddtion error info:' + error);
        }
        return null;
    };
    MessageManager.prototype.getIMMessageAdditionConfig = function () {
        var _this = this;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getMessageAdditionConfig({
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    log_1.default.log('MessageManager::getIMMessageAdditionConfig success rescode:' + rescode + ' data:' + data);
                    if (rescode === 0) {
                        resolve(data);
                    }
                    else {
                        reject(rescode);
                    }
                },
                error: function (e) {
                    log_1.default.error('MessageManager::getIMMessageAdditionConfig fail info:' + e);
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.fetchPersonMessageAddition = function (_a) {
        var _b = _a.mids, mids = _b === void 0 ? [] : _b, _c = _a.channelId, channelId = _c === void 0 ? userData_1.default.get('channelId') : _c;
        return this.fetchIMMessageAddition({ mids: mids, type: 0, channelId: channelId });
    };
    MessageManager.prototype.fetchGroupMessageAddition = function (_a) {
        var _b = _a.mids, mids = _b === void 0 ? [] : _b, _c = _a.channelId, channelId = _c === void 0 ? userData_1.default.get('channelId') : _c;
        return this.fetchIMMessageAddition({ mids: mids, type: 1, channelId: channelId });
    };
    MessageManager.prototype.fetchIMMessageAddition = function (_a) {
        var _this = this;
        var _b = _a.mids, mids = _b === void 0 ? [] : _b, type = _a.type, channelId = _a.channelId;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getIMMessageAddition({
                data: {
                    additions: mids
                        .map(function (element) {
                        return {
                            mid: element
                        };
                    }),
                    chid: channelId,
                    g: type // 0表示单聊，1表示群聊
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0 || !data) {
                        log_1.default.error('MessageManager::fetchIMMessageAddition fail rescode:' + rescode);
                        return reject({ code: rescode });
                    }
                    log_1.default.log('MessageManager::fetchIMMessageAddition suc size:' + (data.additions ? data.additions.length : 0));
                    var parseMsgAddtions = _this._parseMsgAddtionRes(data.additions);
                    resolve({ msgAddtions: parseMsgAddtions });
                },
                error: function (e) {
                    log_1.default.error('MessageManager::fetchIMMessageAddition fail info:' + e);
                    return reject(e);
                },
            });
        });
    };
    /**
     * IM 存储是后端配置天数,最多 1500 个
     *
     * @param {*} {startTime = Date.now() - 15 * 24 * 60 * 60 * 1000, endTime = BIG_TIME}
     * @returns
     * @memberof MessageManager
     */
    MessageManager.prototype.fetchIMRemoteMessagesByTime = function (_a) {
        var _this = this;
        var _b = _a.startTime, startTime = _b === void 0 ? Date.now() - 15 * 24 * 60 * 60 * 1000 : _b, _c = _a.endTime, endTime = _c === void 0 ? BIG_TIME : _c;
        return new promise_1.default(function (resolve, reject) {
            var dataObject = {
                ai: userData_1.default.get('appId'),
                st: startTime,
                et: endTime,
                lm: 200,
                pl: 1,
                type: 1
            };
            log_1.default.log('MessageManager::fetchIMRemoteMessagesByTime info:' + JSON.stringify(dataObject));
            _this.mtdx.HTTP.Msg.chatlistByTime({
                data: dataObject,
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    var messages = [];
                    if (rescode === 0) {
                        messages = _this._parseIMRemoteMsgs(data.res);
                        log_1.default.log('MessageManager::fetchIMRemoteMessagesByTime success rescode:' + rescode
                            + ' message size:' + (messages ? messages.length : 0));
                    }
                    else {
                        log_1.default.error('MessageManager::fetchIMRemoteMessagesByTime fail rescode:' + rescode);
                    }
                    resolve({
                        IMRemoteMessages: messages.reverse(),
                        next: data && data.next ? data.next : -1,
                    });
                },
                error: function (e) {
                    log_1.default.error('MessageManager::fetchIMRemoteMessagesByTime fail info:' + e);
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.fetchPubRemoteMessagesByTime = function (_a) {
        var _this = this;
        var _b = _a.startTime, startTime = _b === void 0 ? Date.now() - 15 * 24 * 60 * 60 * 1000 : _b, _c = _a.endTime, endTime = _c === void 0 ? BIG_TIME : _c;
        return new promise_1.default(function (resolve, reject) {
            var dataObject = {
                st: startTime,
                et: endTime,
                lm: 200,
                pl: 1,
                type: 1
            };
            log_1.default.log('MessageManager::fetchPubRemoteMessagesByTime info:' + JSON.stringify(dataObject));
            _this.mtdx.HTTP.Pub.chatlistByTime({
                data: dataObject,
                success: function (res) {
                    var messageMap = new map_1.default();
                    var messages = [];
                    if (res && res.rescode === 0) {
                        // 换到会话列表消息后,需要做去重，因为服务端第一次获取假如传入Long.MAX就会从最近消息获取数据，第二次有next了就会重会话列表获取数据
                        messages = _this._parsePubRemoteMsgs(res.data.res);
                        messages.forEach(function (message) {
                            var sessionId = sessionIdProcessor_1.default.create({ uid: message.belongTo, channelId: message.channelId, sid: message.sid });
                            if (!messageMap.has(sessionId) || messageMap.get(sessionId).svrTime < message.svrTime) {
                                messageMap.set(sessionId, message);
                            }
                        });
                        log_1.default.log('MessageManager::fetchPubRemoteMessagesByTime success rescode:' + (res ? res.rescode : -1)
                            + ' message size:' + (messages ? messages.length : 0)
                            + ' filter message size:' + (messageMap ? messageMap.size : 0));
                    }
                    else {
                        log_1.default.error('MessageManager::fetchPubRemoteMessagesByTime fail rescode:' + (res ? res.rescode : -1));
                    }
                    resolve({
                        PubRemoteMessages: messageMap.values(),
                        next: res && res.data && res.data.next ? res.data.next : -1,
                    });
                },
                error: function (e) {
                    log_1.default.error('MessageManager::fetchPubRemoteMessagesByTime fail info:' + e);
                    reject(e);
                },
            });
        });
    };
    /**
     * 批量拉取历史消息接口,要求会话类型一致,保证每次批量请求会话在 10 个以内
     *
     * @param {*} {
     *  type: 会话类型,
     *  bs: 会话组信息, IM 见文档:https://km.sankuai.com/page/42253817#id-%E6%A0%B9%E6%8D%AE%E6%97%B6%E9%97%B4%E6%AE%B5%E6%88%96msgid%E6%AE%B5%E8%8E%B7%E5%8F%96%E6%9F%90%E6%B0%94%E6%B3%A1%E9%A1%B5%E7%9A%84%E5%8E%86%E5%8F%B2%E6%B6%88%E6%81%AF, PUB 见文档:https://km.sankuai.com/page/42253263#id-pub%E5%8E%86%E5%8F%B2%E6%B6%88%E6%81%AFmsgid%E6%AE%B5%E6%88%96%E6%97%B6%E9%97%B4%E6%AE%B5%E6%8B%89%E5%8F%96
     * }
     * @returns
     * @memberof MessageManager
     */
    MessageManager.prototype.fetchMultiSessionsHistoryMessagesByTimeRange = function (_a) {
        var _this = this;
        var _b = _a.type, type = _b === void 0 ? constant_1.SESSION_TYPE.CHAT : _b, _c = _a.limit, limit = _c === void 0 ? 20 : _c, _d = _a.sessionDataArray, sessionDataArray = _d === void 0 ? [] : _d, _e = _a.shouldUpdateMessageMap, shouldUpdateMessageMap = _e === void 0 ? true : _e, _f = _a.shouldUpdateMessageMapNotify, shouldUpdateMessageMapNotify = _f === void 0 ? true : _f;
        // 注意sessionDataArray中的单聊、群聊数据有两个关键参数chid和ai，当chid大于0时使用chid获取消息，当chid等于0时，使用ai获取消息，这里的单聊和群聊的ai是指聊天对方的appid
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('MessageManager::fetchMultiSessionsHistoryMessagesByTimeRange session count:' + (sessionDataArray ? sessionDataArray.length : 0));
            var options = {
                data: {
                    u: userData_1.default.get('uid'),
                    ai: userData_1.default.get('appId'),
                    lm: limit,
                    od: 1,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0) {
                        log_1.default.log('MessageManager::fetchMultiSessionsHistoryMessagesByTimeRange fail rescode:' + rescode);
                        return reject({ code: rescode, message: data.message });
                    }
                    else {
                        var parseMessages = _this.parseHistoryRes(data.res);
                        log_1.default.log('MessageManager::fetchMultiSessionsHistoryMessagesByTimeRange success rescode:' + rescode + ' next:' + data.next
                            + ' messages size:' + (parseMessages ? parseMessages.length : 0));
                        resolve({ msgs: parseMessages, next: data.next });
                    }
                },
                error: function (xhr, status, err) {
                    log_1.default.error('MessageManager::fetchMultiSessionsHistoryMessagesByTimeRange fail xhr:' + xhr + ' status:' + status + ' err:' + err);
                    return reject({ code: constant_2.SDKRESCODE.UNKNOWN_ERROR, message: 'xhr:' + xhr + ' status:' + status + ' err:' + err });
                },
            };
            switch (type) {
                case constant_1.SESSION_TYPE.CHAT: {
                    options.data.bs = sessionDataArray;
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CHAT2: {
                    options.data.bs = sessionDataArray;
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.GROUP_CHAT: {
                    options.data.bs = sessionDataArray;
                    _this.mtdx.HTTP.Msg.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT: {
                    options.data.ps = sessionDataArray;
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT2: {
                    options.data.ps = sessionDataArray;
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT: {
                    options.data.ps = sessionDataArray;
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT2: {
                    options.data.ps = sessionDataArray;
                    _this.mtdx.HTTP.Pub.historyOfChannelByRange(options);
                    break;
                }
            }
        }).then(function (res) {
            var messageData = {};
            res.msgs.forEach(function (message) {
                if (!messageData[message.sessionId]) {
                    messageData[message.sessionId] = [message];
                }
                else {
                    messageData[message.sessionId].push(message);
                }
            });
            for (var sessionId in messageData) {
                var _a = sessionIdProcessor_1.default.parseSessionId(sessionId), uid = _a.uid, channelId = _a.channelId, sid = _a.sid;
                if (shouldUpdateMessageMap && shouldUpdateMessageMapNotify) {
                    _this.putMessagesInMap(uid, channelId, sid, messageData[sessionId], constant_1.MESSAGE_SOURCE.HISTORY);
                }
            }
            return messageData;
        });
    };
    MessageManager.prototype.shouldSetHeadersWhenGetFileBlob = function (_a) {
        var url = _a.url;
        var env = userData_1.default.get('env');
        return this.mtdx.HTTP.Common.shouldSetHeadersWhenGetFileBlob({ url: url, env: env });
    };
    MessageManager.prototype.getFileBlob = function (_a) {
        var url = _a.url, token = _a.token;
        return this.mtdx.HTTP.Common.getFileBlob({ url: url, token: token });
    };
    MessageManager.prototype.getAuthFreeTempFileURL = function (_a) {
        var _this = this;
        var url = _a.url, token = _a.token;
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('MessageManager::getAuthFreeTempFileURL url:' + url + ' token:' + token);
            _this.mtdx.HTTP.Common.getAuthFreeTempFileURL({
                method: 'GET',
                headers: {
                    'X-Xmftk': token,
                },
                data: {
                    originalUrl: url,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        log_1.default.log('MessageManager::getAuthFreeTempFileURL success url:' + url + ' dataurl:' + data.url);
                        resolve({
                            url: data.url,
                        });
                    }
                    else {
                        log_1.default.log('MessageManager::getAuthFreeTempFileURL fail url:' + url);
                        reject(rescode);
                    }
                },
                fail: function (e) {
                    log_1.default.error('MessageManager::getAuthFreeTempFileURL fail info:' + e);
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.sendGroupReceiptMessage = function (_a) {
        var _b = _a.toGuid, toGuid = _b === void 0 ? '' : _b, _c = _a.channelId, channelId = _c === void 0 ? 0 : _c, _d = _a.messageItems, messageItems = _d === void 0 ? [] : _d;
        var binaryMessage = opposite_read_creator_1.default.createGroupReceiptMessage({
            fromUid: config_manager_1.default.getConfig().uid,
            toGuid: toGuid,
            channelId: channelId,
            messageItems: messageItems,
        });
        this.mtdx.imSDK.send(binaryMessage);
        return {
            uuid: binaryMessage.receiptUid,
        };
    };
    MessageManager.prototype.getGroupReceiptConfig = function (_a) {
        var _this = this;
        var appId = _a.appId;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getGroupReceiptConfig({
                data: {
                    appId: appId,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        var channelMap_1 = {};
                        data.forEach(function (element) {
                            channelMap_1[element.channel] = element.isopen === 1 ? true : false;
                        });
                        resolve({ channelMap: channelMap_1 });
                    }
                    else {
                        reject(rescode);
                    }
                },
                fail: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.getGroupReceiptMessageList = function (_a) {
        var _this = this;
        var mids = _a.mids;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getGroupReceiptMessageList({
                data: {
                    mids: mids,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        var result_1 = {};
                        data.forEach(function (element) {
                            result_1[element.msgIdStr] = {
                                receiptUid: element['receipt_uid_str'],
                                unreceiptUid: element['unreceipt_uid_str'],
                            };
                        });
                        resolve({ uidList: result_1 });
                    }
                    else {
                        reject(rescode);
                    }
                },
                fail: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.getGroupReceiptMessageCount = function (_a) {
        var _this = this;
        var mids = _a.mids;
        return new promise_1.default(function (resolve, reject) {
            _this.mtdx.HTTP.Msg.getGroupReceiptMessageCount({
                data: {
                    mids: mids,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode === 0) {
                        var result = {};
                        for (var i in data) {
                            result[data[i].msgIdStr] = {
                                total: data[i]['total_count'],
                                receipt: data[i]['receipt_count']
                            };
                        }
                        resolve({ countList: result });
                    }
                    else {
                        reject(rescode);
                    }
                },
                fail: function (e) {
                    reject(e);
                },
            });
        });
    };
    MessageManager.prototype.setNoMoreMessages = function () {
        this._shouldReceiveMessage = false;
        log_1.default.warn('MessageManager::不在接受消息,如果需要重新接受消息请重新登录');
    };
    MessageManager.prototype.fetchOfflineDataMessage = function () {
        if (!this.mtdx.HTTP.DATA) {
            return;
        }
        var options = {
            data: {
                lm: 1000,
                os: 0 //偏移量
            },
            success: function (_a) {
                var rescode = _a.rescode, data = _a.data;
                log_1.default.info('MessageManager::fetchOfflineDataMessage success');
            },
            error: function (error) {
                log_1.default.error('MessageManager::fetchOfflineDataMessage fail info:' + error);
            },
        };
        this.mtdx.HTTP.DATA.offline(options);
    };
    MessageManager.prototype.fetchChatListDelInfo = function () {
        this.fetchSessionListDelInfo(constant_3.SVID.SVID_IM);
        this.fetchSessionListDelInfo(constant_3.SVID.SVID_PUB);
    };
    MessageManager.prototype.fetchSessionListDelInfo = function (svid) {
        var _this = this;
        var requestTime = timer_1.default.get();
        return new promise_1.default(function (resolve, reject) {
            var lastSuccessTime = localData_1.default.get(svid == constant_3.SVID.SVID_IM ? 'im_session_list_info_success_time' : 'pub_session_list_info_success_time') || 0;
            log_1.default.log('MessageManager::fetchSessionListDelInfo startTime:' + lastSuccessTime + ' endTime:' + requestTime + ' svid:' + svid);
            _this.fetchSessionListInfoCycle({ svid: svid, prev: new Array(), startTime: lastSuccessTime, endTime: requestTime, fields: ['del'], resolve: resolve, reject: reject });
        }).then(function (sessionInfoArray) {
            try {
                log_1.default.log('MessageManager::fetchSessionListDelInfo complete sessionInfoArray size:' + sessionInfoArray.length + ' svid:' + svid + ' time:' + requestTime);
                localData_1.default.set(svid == constant_3.SVID.SVID_IM ? 'im_session_list_info_success_time' : 'pub_session_list_info_success_time', requestTime);
                var deleteMessageArray_1 = [];
                sessionInfoArray.forEach(function (item) {
                    var type = item['type'] || '';
                    if (type === 'delAll' || type === 'delChat') {
                        var dataObject = null;
                        if (type === 'delAll') {
                            dataObject = {
                                action: svid == constant_3.SVID.SVID_IM ? 'imChatAll' : 'pubChatAll',
                                channels: [(item['chid'] || 0)],
                                cleanTs: item['cleanTs']
                            };
                        }
                        else if (type == 'delChat') {
                            dataObject = {
                                action: svid == constant_3.SVID.SVID_IM ? 'imchat' : 'pubchat',
                                chat: [{
                                        u: item['u'] || item['b'] || '',
                                        pu: item['pu'] || '',
                                        chid: item['chid'] || 0,
                                        sid: item['sid'] || ''
                                    }]
                            };
                        }
                        var dataMessageObject = parse_data_message_1.default({
                            type: 152,
                            msgId: 0,
                            data: JSON.stringify(dataObject),
                            channel: item['chid'],
                            deviceId: userData_1.default.get('deviceId'),
                        });
                        deleteMessageArray_1.push(dataMessageObject);
                    }
                });
                if (deleteMessageArray_1.length > 0) {
                    event_emitter_1.default.emit(event_emitter_1.EVENT_NAME.DATA_MESSAGE_OFFLINE, { messages: deleteMessageArray_1 });
                }
                return sessionInfoArray;
            }
            catch (error) {
                log_1.default.error('MessageManager::fetchSessionListDelInfo parse error:' + error);
                return promise_1.default.reject(error);
            }
        }).catch(function (error) {
            log_1.default.error('MessageManager::fetchSessionListDelInfo error:' + error);
            return promise_1.default.reject(error);
        });
    };
    MessageManager.prototype.fetchSessionListInfoCycle = function (_a) {
        var _this = this;
        var svid = _a.svid, prev = _a.prev, startTime = _a.startTime, endTime = _a.endTime, fields = _a.fields, resolve = _a.resolve, reject = _a.reject;
        log_1.default.log('MessageManager::fetchSessionListInfoCycle prev:' +
            (prev ? prev.length : 0) + ' startTime:' + startTime + ' endTime:' + endTime + ' svid:' + svid);
        this.fetchSessionListInfoOnce({ svid: svid, startTime: startTime, endTime: endTime, fields: fields }).then(function (response) {
            var next = response.next;
            var rescode = response.rescode;
            var sessionListInfo = response.data ? response.data : [];
            log_1.default.log('MessageManager::fetchSessionListInfoCycle complete next:' + next + ' prev:' + (prev ? prev.length : 0) + ' cur:' + (sessionListInfo ? sessionListInfo.length : 0)
                + ' rescode:' + rescode + ' svid:' + svid);
            try {
                if (rescode === 0) {
                    if (prev && sessionListInfo) {
                        sessionListInfo.forEach(function (item) {
                            prev.push(item);
                        });
                    }
                    if (next > 0 && (prev && prev.length <= 1000)) {
                        _this.fetchSessionListInfoCycle({ svid: svid, prev: prev, startTime: startTime, endTime: next, fields: fields, resolve: resolve, reject: reject });
                    }
                    else {
                        resolve(prev);
                    }
                }
                else {
                    reject(rescode);
                }
            }
            catch (error) {
                log_1.default.error('MessageManager::fetchSessionListInfoCycle parse error:' + error);
                reject(error);
            }
        }).catch(function (error) {
            log_1.default.error('MessageManager::fetchSessionListInfoCycle error:' + error);
            reject(error);
        });
    };
    MessageManager.prototype.fetchSessionListInfoOnce = function (_a) {
        var _this = this;
        var svid = _a.svid, startTime = _a.startTime, endTime = _a.endTime, fields = _a.fields;
        return new promise_1.default(function (resolve, reject) {
            var dataObject = {
                st: startTime,
                et: endTime,
                fields: fields
            };
            log_1.default.log('MessageManager::fetchSessionListInfoOnce info:' + JSON.stringify(dataObject) + ' svid:' + svid);
            var requestOption = {
                data: dataObject,
                success: function (response) {
                    resolve(response);
                },
                error: function (error) {
                    log_1.default.error('MessageManager::fetchSessionListInfoOnce fail info:' + error);
                    reject(error);
                },
            };
            if (svid == constant_3.SVID.SVID_IM) {
                _this.mtdx.HTTP.Msg.getChatlistInfo(requestOption);
            }
            else if (svid == constant_3.SVID.SVID_PUB) {
                _this.mtdx.HTTP.Pub.getChatlistInfo(requestOption);
            }
            else {
                log_1.default.error('MessageManager::fetchSessionListInfoOnce not found svid:' + svid);
            }
        });
    };
    MessageManager.prototype.fetchLastNormalMessage = function (_a) {
        var _this = this;
        var uid = _a.uid, type = _a.type, channelId = _a.channelId, _b = _a.mid, mid = _b === void 0 ? BIG_MID : _b, sid = _a.sid, _c = _a.jts, jts = _c === void 0 ? 0 : _c;
        return new promise_1.default(function (resolve, reject) {
            log_1.default.log('MessageManager::fetchLastNormalMessage uid:' + uid + ' type:' + type
                + ' channelId:' + channelId + ' sid:' + sid
                + ' mid:' + mid);
            var appId = config_manager_1.default.getConfig().appId;
            var options = {
                data: {
                    id: mid,
                },
                success: function (_a) {
                    var rescode = _a.rescode, data = _a.data;
                    if (rescode !== 0 || !data) {
                        log_1.default.error('MessageManager::fetchLastNormalMessage fail rescode:' + rescode);
                        return reject({ code: rescode, message: data ? data.message : '' });
                    }
                    var parseMessages = _this.parseHistoryRes(data.res);
                    log_1.default.log('MessageManager::fetchLastNormalMessage suc ' + ' messages:' + message_util_1.default.getMessageArrayPrint(parseMessages));
                    resolve({ msgs: parseMessages });
                },
                error: function (e) {
                    log_1.default.error('MessageManager::fetchLastNormalMessage fail info:' + e);
                    return reject(e);
                },
            };
            switch (type) {
                case constant_1.SESSION_TYPE.CHAT: {
                    options.data.bs = [{ b: uid, ai: appId, g: 0, chid: channelId, jts: jts }];
                    _this.mtdx.HTTP.Msg.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CHAT2: {
                    options.data.bs = [{ b: uid, ai: appId, g: 0, chid: channelId, sid: sid, jts: jts }];
                    _this.mtdx.HTTP.Msg.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.GROUP_CHAT: {
                    options.data.bs = [{ b: uid, ai: appId, g: 1, chid: channelId, jts: jts }];
                    _this.mtdx.HTTP.Msg.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT: {
                    options.data.ps = [{ u: uid, pu: 0, chid: channelId }];
                    _this.mtdx.HTTP.Pub.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.PUB_CHAT2: {
                    options.data.ps = [{ u: uid, pu: 0, chid: channelId, sid: sid }];
                    _this.mtdx.HTTP.Pub.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT: {
                    var _a = uid.split('_'), pubId = _a[0], peerUid = _a[1];
                    options.data.ps = [{ u: pubId, pu: peerUid, chid: channelId }];
                    _this.mtdx.HTTP.Pub.getPreviousMessage(options);
                    break;
                }
                case constant_1.SESSION_TYPE.CS_CHAT2: {
                    var _b = uid.split('_'), pubId = _b[0], peerUid = _b[1];
                    options.data.ps = [{ u: pubId, pu: peerUid, chid: channelId, sid: sid }];
                    _this.mtdx.HTTP.Pub.getPreviousMessage(options);
                    break;
                }
            }
        });
    };
    return MessageManager;
}());
exports.default = new MessageManager();


//# sourceURL=webpack://MTDX/./src/extra/managers/message-manager.ts?